let lifeData = uni.getStorageSync('lifeData') || {};
let $user = lifeData.$user || {};
lifeData.core=lifeData.core||{}
const state={
	userInfo:$user.userInfo||{
		uid:0, //用户编号
		_id:'',
		avatar:'',//头像
		nickname:'',//昵称
		username:'',//用户名
		mobile:'', //手机号
		desc:'',   //介绍
        extra:{},//其它属性
		permission:[]  ,//权限值
		role:[]  //角色组
	},
	userAccount:{  //账户信息
		experience:'',
		balance:0, //收入 用户余额转入
		fans:'',
		follow:'',
		gold:0,  //代金券 赠送
		income:0,//收入 用户直接充值
		money:0 //余额 充值
	},
	theme:lifeData.core.theme||'',
	themeClass:lifeData.core.themeClass||{
		head:{}
	},
	themeColor:lifeData.core.themeColor||{},
	localAccount:lifeData.core.localAccount||{},
	token:lifeData.core.token||'',
	taskList:[],
	taskStart:false,
	dictStore:lifeData.core.dictStore ||{},  //字典
	hooks:{},
	publishs:{},
	subscribes:{},
	version:lifeData.core.version || {} //系统版本

};
const getters={
    ThemeName:(state)=>{
        return state.theme ||uni.wy.vk.getVuex('core.theme')  || uni.wy.config.App.theme
    },
    ThemeClass:(state)=>{
        var themeName=state.theme || uni.wy.vk.getVuex('core.theme') || uni.wy.config.App.theme
        let themeClass=uni.wy.config.Theme 
        return themeClass[themeName]?themeClass[themeName]:{}
        
    },
	DictStore:(state)=>{
		let {Dict}= uni.wy.config
		var obj=uni.wy.pubfn.deepMerge(Dict,state.dictStore)
		return obj
	},
	Version:(state)=>{
		return state.version
	},
	Hooks:(state)=>{
		let {Hooks}= uni.wy.config
		var obj=uni.wy.pubfn.deepMerge(Hooks,state.hooks)
		return obj
	},
    Permission:(state)=>{
        let model=uni.wy.vk.getVuex('$user.userInfo') || {}
        let user={
        	...state.userInfo,
        	...model
        }
        let {permission}=user
        return permission ||[]
    },
	UID:(state)=>{
		let model=uni.wy.vk.getVuex('$user.userInfo') || {}
		let user={
			...state.userInfo,
			...model
		}
		let {uid,_id}=user
		return uid || _id
	},
	IsLogin:(getters)=>{
		let model=uni.wy.vk.getVuex('$user.userInfo') || {}
		let user={
			...state.userInfo,
			...model
		}
		let {uid,_id}=user
		if(uid || _id){
			return true
		}
		else{
			return false
		}
	},
	UserInfo: (state) => {
		let model=uni.wy.vk.getVuex('$user.userInfo') || {}
		let user={
			...state.userInfo,
			...model
		}
		let {nickname,username,avatar,uid,_id}=user
		if(!nickname){
			user.nickname=username
		}
		if(!avatar){
			user.avatar=uni.wy.localUrl('logo') //uni.wy.config.Local.imgs.logo
		}
		if(!uid){
			user.uid=_id
		}
		return user
	},
	UserAccount:state=>{

		return {
			experience:0,
			balance:0,
			fans:0,
			follow:0,
			gold:0,
			income:0,
			money:0 ,
			...state.userAccount
		}
	},
	//本地账户
	LocalAccount: (state) => {
		let userModel=uni.wy.vk.getVuex('$user.userInfo') || {}

		var localAccount=uni.wy.vk.getVuex('core.localAccount') || {}
		let locals={}
		if(userModel&&userModel.hasOwnProperty('_id')){
			Object.assign(localAccount,{[userModel._id]:userModel})
		}
		for(let key in localAccount){
			var model={
				...state.userInfo,
				...localAccount[key]
			}
			let {_id}=model
			Object.assign(locals,{[_id]:model})
		}
		return locals
	}
};
const mutations={
    setTheme:(state,model)=>{
       let {theme}=model
       if(theme){
           uni.wy.vk.setVuex('core.theme',theme) 
           state.theme=theme
       }
    },
	setVersion:(state,model)=>{
		state.version=Object.assign(state.version,model)
		uni.wy.vk.setVuex('core.version',state.version)
	},
	pushTask:(state,model)=>{
		state.taskList.push(model)
	},
	setUserAccount:(state,model)=>{
		state.userAccount=model
		//console.log(state.userAccount)
	},
	resetUser:(state,data)=>{
		uni.wy.callFunctionUtil.deleteToken ()
		state.userAccount={}
	},
    setUser:(state,data)=>{
        let {token,userInfo,tokenExpired}=data
          //uid:0,
        //  _id:'',
        //  avatar:'',
        //  nickname:'',
        //  username:'',
         // mobile:'',
          tokenExpired=tokenExpired?tokenExpired:(uni.wy.pubfn.unix()+60*60*24*30)*1000
          if(token ){
              uni.wy.vk.callFunctionUtil.saveToken({token,tokenExpired})
          }
          if(userInfo){
              uni.wy.vk.callFunctionUtil.updateUserInfo({userInfo})
          }
    },
    setToken:(state,data)=>{
        
    },
	setHooks:(state,model)=>{
		state.hooks=model
	},
	resetDictStore:(state,model)=>{
		state.dictStore=model
		uni.wy.vk.setVuex('core.dictStore',state.dictStore)
	},
	setDictStore:(state,model)=>{
		state.dictStore=Object.assign(state.dictStore,model)
		uni.wy.vk.setVuex('core.dictStore',state.dictStore)
	},
	publish:(state,model)=>{
		let {name,data}=model
		state.publishs=Object.assign(state.publishs,{[name]:model})
		//自动触发
		if(state.subscribes.hasOwnProperty(name)){
			const list=state.subscribes[name]
			for(let i=0;i<list.length;i++){
				let {param,fn,name,uuid}=list[i]
				let {auto,onece}=param
				if(auto && uni.wy.pubfn.isFunction(fn)){
					fn({param,name,uuid,data})
				}
			}

		}
		uni.wy.log(state.publishs)

	},
	unpushlish:(state,model)=>{
		let {name}=model
		if(state.publishs.hasOwnProperty(name)){
			delete state.publishs[name]
		}
	},
	subscribe:(state,model)=>{
		let {name,param}=model   //,fn,param,uuid
		model.param={
			auto:false, //自动触发
			...param
		}
		if(state.subscribes.hasOwnProperty(name)){
			let {uuid}=model
			if(uuid){
				var index=state.subscribes[name].findIndex((e)=>{
					return e.uuid && e.uuid === uuid
				})
				if(index>=0){
					return
				}
			}
			state.subscribes[name].push(model)
		}
		else{
			state.subscribes=Object.assign(state.subscribes,{[name]:[model]})
		}
		uni.wy.log(state.subscribes)
	},
	doemit:(state,model)=>{
		let {name,uuid,onece,clear}=model
		if(uuid && state.publishs.hasOwnProperty(name)){
			let {data}=state.publishs[name]
			const copys=state.subscribes
			for(let key in copys){
				let list=copys[key]
				var index=list.findIndex((e)=>{
					return e.uuid === uuid
				})
				if(index>=0){
					let {param,fn}=list[index]
					if(uni.wy.pubfn.isFunction(fn)){
						if(onece){
							state.subscribes[key].splice(index,1)
						}
						fn({param,name,data,uuid})
					}
					break
				}
			}
			//是否删除发布
			if(clear){
				delete state.publishs[name]
			}


		}
	},
	unsubscribe:(state,model)=>{
		let {name,uuid,clear}=model
		if(name && state.subscribes.hasOwnProperty(name)){
			delete state.subscribes[name]
		}
		if(name&&clear && state.publishs.hasOwnProperty(name)){
			delete state.publishs[name]
		}
		if(uuid){
			const copys=state.subscribes
			for(let key in copys){
				let list=copys[key]
				var index=list.findIndex((e)=>{
					return e.uuid === uuid
				})
				if(index>=0){
					state.subscribes[key].splice(index,1)
					break
				}
			}
		}
		uni.wy.log(state.subscribes)
	}
};
const actions={
    setTheme({commit},model){
        commit('setTheme',model)
    },
    setUserLogout({commit}){
        console.debug('-----setUserLoginOut')
        commit('resetUser',{})
        commit('resetDictStore',{})
    },
    //外部登陆对接
    setUserLogin({commit},data){
		commit('setUser',data)
    },
    /**
     * 用户登入
     * @param {*} option 调用callFunction传入的参数
     * @param {*} type 获取字典值的方法，login 账号密码,loginBySms 短信登录,loginByUniverify,loginByEmail,loginByWeixin
     */
    userLogin({commit},{type='login',data={},option={}}){ 
        return new Promise((resolve, reject)=>{
            uni.wy.callFunction({
                url:'wyapp/pub/action',
                do:'user/'+type,
                data,
				errorToast:true,
				title:'请求中...',
				...option,
                success(res){ 
                    commit('setUser',res.data)
                    resolve(res)
                },
                fail(err){
                    reject(err)
                }
            })
        })
    },
    userLogout({commit},option){
        //不论是否成功
        commit('resetUser',{})
        commit('resetDictStore',{})
        return new Promise((resolve, reject)=>{
            uni.wy.callFunction({
                url:'wyapp/pub/action',
                do:'user/logout',
                ...option,
                success(res){ 
                    resolve(res)
                },
                fail(err){ 
                    reject(err)
                } 
            })
        })
    },
	setVersion({commit},option={}){
		commit('setVersion',option)
	},
	/**
	 *
	 * @param {*} 新增设置字典
	 */
	setDictStore({commit},option={}){
		commit('setDictStore',option)
	},
	resetDictStore({commit},option={}){
		commit('resetDictStore',option)
	},
    async getDictStore({},keys=[],isCache=false){
        return new Promise((resolve, reject)=>{
            uni.wy.callFunction({
                url:'dictStore',
                data:{keys},
                cache:false,
                success(res){
                    resolve(res.data)
                }
                ,fail(err){
                    reject(err)
                }
            })
        })
    },
	/**
	 *
	 * @param {*} keys 需加载的字典key集合
	 * @param {*} func 获取字典值的方法
	 * @param {*} prekeys 需要预加载的字典key集合
	 */
	async loadDictStore({commit,getters,dispatch},option={}){ 
		let {expired,dictFun,cachekey}=uni.wy.config.Local.dictStore
	    dictFun=dictFun?dictFun:'core/getDictStore'
		let {keys,func,prekeys,ispreload,success,cache,reskeys,cacheTime}=option
		reskeys=reskeys?reskeys:{} ,//结果组装的key
		cacheTime=cacheTime?cacheTime:expired
	    var isCache=cacheTime?true:false
		if(cache === false){
			isCache = false
		}
	    let result={}
	    let noKeys=[]
        keys.forEach((key)=>{ 
            if(isCache){
               var res = uni.wy.pubfn.cache.get([cachekey,key].join('.'),null)
               if(res == null){
                 noKeys.push(key)
               }
               else{
               	var reskey = reskeys.hasOwnProperty(key)?reskeys[key]:key
               	result=Object.assign(result,{[reskey]:res})
               }  
            } 
            else{
               noKeys.push(key) 
            }
        	
        }) 
	    console.debug((ispreload?'预':'已')+'加载字典:',result)
	    return new Promise((resolve, reject)=>{
			if(noKeys.length>0 ){  
				new Promise((a,r)=>{
					if(func){
					    func(noKeys,isCache).then((result)=>{
							a(result)
						}).catch((err)=>{
							r(err)
						})
					}
					else if(dictFun){ 
					    uni.wy.dispatch(dictFun,noKeys,isCache).then((result)=>{
							a(result)
						}).catch((err)=>{
							r(err)
						})
					} 
				}).then((newReuslt)=>{
					for(let key in newReuslt){
						var res = newReuslt[key]
						var reskey = reskeys.hasOwnProperty(key)?reskeys[key]:key
						result=Object.assign(result,{[reskey]:res})
                        if(isCache){
                           uni.wy.pubfn.cache.set([cachekey,key].join('.'),res,cacheTime) 
                        } 
					} 
					if(prekeys&&prekeys.length>0){
					    setTimeout(()=>{
					        dispatch('loadDictStore',{
					            keys:prekeys,func,prekeys:null,ispreload:true,cacheTime,cache
					        })
					    },500)
					}
					if(success){
					    success(result)
					}
					resolve(result)
				}).catch((err)=>{
					reject(err)
				})
			}  
	       
	    })
	},
	/**
	 *
	 * @param {*} keys 需加载的字典key集合
	 * @param {*} func 获取字典值的方法
	 * @param {*} prekeys 需要预加载的字典key集合
	 */
	async loadDictStore1({commit,getters,dispatch},option={}){
		 let {expired,dictFun}=uni.wy.config.Local.dictStore
         dictFun=dictFun?dictFun:'core/getMultiDictDetail'
		 let {keys,func,prekeys,ispreload,success,cache}=option
		 if(expired){
			  var cacheTime=uni.wy.pubfn.cache.S({
					key:'dictStore.expired'
				})
				if(!cacheTime){
					commit('resetDictStore',{})
					uni.wy.pubfn.cache.S({
						key:'dictStore.expired',
						data:1,
						time:expired
					})
				}
		 }
        const isCache=cache||expired?false:true
        const obj=getters.DictStore //{key:value} 
        let result={}
        let noKeys=[]
        keys.forEach((key)=>{
            if(obj.hasOwnProperty(key)){
                result=Object.assign(result,{[key]:obj[key]})
            }
            else{
                noKeys.push(key)
            }
        })
        if(noKeys.length>0 ){
            var newReuslt={}
            if(func){
                newReuslt=await func(noKeys,isCache)
            }
            else if(dictFun){
                newReuslt=await uni.wy.dispatch(dictFun,noKeys,isCache)
            }
          commit('setDictStore',newReuslt)
            result=Object.assign(result,newReuslt)
        }
        if(prekeys&&prekeys.length>0){
            setTimeout(()=>{
                dispatch('loadDictStore',{
                    keys:prekeys,func,prekeys:null,ispreload:true
                })
            },500)
        }
        console.debug((ispreload?'预':'已')+'加载字典:',result)
        return new Promise((resolve, reject)=>{
            if(success){
                success(result)
            }
            resolve(result)
        })
	},


	/**
	 * 发布 用于异步跨页面通讯
	 * @param {String} name 唯一标识
	 * @param {Object} data 附加数据
	 */
	publish({commit},option={}){
		option={
			name:'',
			data:{},
			...option
		}
		commit('publish',option)
	},
	/**
	 * 订阅 用于异步跨页面通讯
	 * @param {String} name 订阅标识
	 * @param {Function} fn 回调方法
	 * @param {Object} param auto 自动触发
	 * @param {String} uuid 唯一编号，用于取消订阅
	 */
	subscribe({commit},option={}){
		//name,fn,uuid='',param={}
		option={
			name:'',
			fn:null,
			uuid:'',
			param:{},
			...option
		}
		commit('subscribe',option)
	},
	/**
	 * 取消订阅 用于跨页面通讯
	 * @param {Object} param name或者uuid
	 */
	unsubscribe({commit},param){
		commit('unsubscribe',param)
	},
	/**
	 * 触发事件需订阅的时候设置uuid
	 * @param {String} name 订阅标识
	 * @param {String} uuid 唯一标识
	 * @param {Object} data  传入参数
	 */
	doemit({commit},option={}){
		option={
			name:'',
			uuid:'',
			onece:true,
			clear:false,
			...option
		}
		commit('doemit',option)
	},
	StartTask({commit},isStart=true){


	},
	PushTask({commit},taskFun){
		commit('pushTask',taskFun)
		if(state.taskStart){

		}
	},
	
	async checkUserSession({commit}){
		return new Promise((resolve, reject)=>{
			uni.wy.callFunction({
				url:'user/pub/userSession', 
				success(res) {
                    if(res.data && res.data.userInfo){ 
                        //更新用户信息
                         uni.wy.callFunctionUtil.updateUserInfo({userInfo})
                    } 
					resolve(res.data)
				},fail() {
					commit('resetUser',{})
				}
			})

		})

	},
	async getUserAccount({commit},data,option={}){
		return new Promise((resolve, reject)=>{
			uni.wy.callFunction({
				url:'user/kh/userAccount',
				success(res) {
					if(res.data){
						commit('setUserAccount',res.data)
					}
					resolve(res.data)
				}
			})

		})

	},
	//加载应用配置
	async loadAppConfig({commit}){
		return new Promise((resolve, reject)=>{
			uni.wy.callFunction({
				url:'appConfig',
				success(res) {
					if(res.data){
						let {hooks,dictStore,config}=res.data
						if(hooks){
							commit('setHooks',hooks)
						}
						if(dictStore){
							commit('setDictStore',dictStore)
						}
						if(config){
							uni.wy.setLocalConfig(config)
                            uni.wy.publish('appConfig',config)
						}
					}
					resolve(res.data)
				}
			})
		})
	}
};
export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}
